$(function () {
  // 需求:获取用于信息渲染欢迎和头像
  getUserInfo()
  // 需求2:退出
  $('#logout').on('click', function () {
    // layer里面询问框，点击确认才会执行回调函数里面的代码
    layer.confirm(
      '确认退出登录?',
      { icon: 3, title: '提示' },
      function (index) {
        // do something
        // 销毁token, 跳转到登录页
        localStorage.removeItem('token')
        location.href = '/login.html'
        // location.href = '/login.html'
        // // 自带的代码,关闭询问框
        // layer.close(index)
      }
    )
  })
})

function getUserInfo() {
  axios({
    url: '/my/userinfo'
    // headers: {
    //   Authorization: localStorage.getItem('token')
    // }
  }).then(({ data: res }) => {
    if (res.status !== 0) {
      return layui.layer.msg(res.message)
    }
    //   渲染
    renderAvatar(res.data)
  })
}

function renderAvatar(user) {
  let name = user.nickname || user.username
  $('.welcome').html('欢迎&nbsp;' + name)
  console.log(name)
  if (user.user_pic !== null) {
    $('.avatar-text').hide()
    $('.layui-nav-img').show().attr('src', user.user_pic)
  } else {
    $('.layui-nav-img').hide()
    let first = name[0].toUpperCase()
    $('.avatar-text').show().html(first)
  }
}
